package edu.sysu.demo.petstore.dog.config;

import com.google.common.io.BaseEncoding;
import edu.sysu.demo.petstore.token.JWTIssuer;
import edu.sysu.demo.petstore.token.JWTVerifier;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http// 基于token，所以不需要session
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)

        .and()
        .csrf().disable()
        .anonymous()

        .and()
        .authorizeRequests()
        .antMatchers(HttpMethod.POST, "/account/register").permitAll()
        .antMatchers(HttpMethod.POST, "/account/login").permitAll()
        .antMatchers(HttpMethod.GET, "/key/public").permitAll()
        .anyRequest().hasRole("users");
  }

  @Bean
  public JWTIssuer jwtIssuer() {
    return new JWTIssuer();
  }

  @Bean
  public JWTVerifier jwtVerifier() {
    return new JWTVerifier();
  }

  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

  @Bean
  public BaseEncoding baseEncoding() {
    return BaseEncoding.base64();
  }

  @Bean
  public BouncyCastleProvider bouncyCastleProvider() {
    return new BouncyCastleProvider();
  }
}
